<template>
  <div class="root">
    <m-header title="上传头像">
      <div slot="left" v-on:click="$router.go(-1)"><img class="m-icon-img margin-right-10" src="../assets/images/menu_back.png" /></div>
      <div slot="right"><img class="m-icon-img margin-right-10" src="../assets/images/menu_more.png" /></div>
    </m-header>

    <div class="content" id="content">

      <!--隐藏input，把样式写到label上，点击label就是对input进行操作。-->
      <!--<input id="filechooser" type="file" accept="image/*;" capture="camera" style="display:none;" />-->
      <input id="filechooser" type="file" accept="image/*;" style="display:none;" />
      <label for="filechooser" id="filechooser_label"> 选择文件 </label>

      <!--<div id="preview_box2"></div>-->
      <br/>
      <img alt="Image Previewer" id="previewer" :src="avatarUrl" />

    </div>
  </div>
</template>

<script>
  import mHeader from '../components/header'
  import util from '../util/util.js'

  export default {
    components: {
      mHeader,
    },
    data() {
      return {}
    },
    computed: {
      avatarUrl() {
        return this.$store.state.myInfo.avatar;
      }
    },
    methods: {

      init() {
        var _this = this;
        var filechooser = document.getElementById('filechooser');
        var previewer = document.getElementById('previewer');
        // 200 KB 对应的字节数
        var maxsize = 200 * 1024;

        filechooser.onchange = function () {
          var files = this.files;
          var file = files[0];

          // 接受 jpeg, jpg, png 类型的图片
          if (!/\/(?:jpeg|jpg|png)/i.test(file.type)) {
            return util.toast('不支持的文件格式');
          }

          var reader = new FileReader();

          //onload是一个异步回调，当文件读取完执行该方法内代码
          reader.onload = function () {
            var result = this.result;
            _this.compressDataURL(result);
          };

          reader.readAsDataURL(file);
        };
      },

      //压缩并裁剪
      compressDataURL(dataURL) {
        var _this = this;
        const img = new window.Image();
        // onload
        img.onload = function () {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          //   canvas.width = 100 * ratio.width;
          //   canvas.height = 100 * ratio.height;
          canvas.width = 240;
          canvas.height = 240;
          const RATIO = canvas.width / canvas.height;
          let cutx = 0;
          let cuty = 0;
          let cutw = img.width;
          let cuth = img.height;
          if (cutw / cuth > RATIO) {
            // 宽超过比例了
            let realw = cuth * RATIO;
            cutx = (cutw - realw) / 2;
            cutw = realw;
          } else if (cutw / cuth < RATIO) {
            // 长超过比例了
            let realh = cutw / RATIO;
            cuty = (cuth - realh) / 2;
            cuth = realh;
          }
          ctx.drawImage(img, cutx, cuty, cutw, cuth, 0, 0, canvas.width, canvas.height);
          const ndata = canvas.toDataURL('image/jpeg', 0.92);
          document.getElementById('previewer').src = ndata;
          _this.uploadImg(ndata);
        };
        img.src = dataURL;
      },

      uploadImg(dataUrl) {
        var _this = this;
        const blob = this.dataURLtoBlob(dataUrl);
        const formData = new FormData();
        formData.append('avatar', blob);

        let xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
          //服务器连接已建立
          if (xhr.readyState === 1) {
            _this.$store.dispatch('showLoading');
          }
          //请求已完成，且响应已就绪
          if (xhr.readyState === 4) {
            _this.$store.dispatch('hideLoading');
            console.log(xhr.responseText);
            if (xhr.status === 200) {
              // 上传成功，获取到结果 results
              console.log(xhr.responseText);
              let response = JSON.parse(xhr.responseText);
              util.toast(response.msg);
              if (response.code === '0') {
                if (response.data.avatar !== null) {
                  _this.$store.dispatch('UPDATE_MY_AVATAR', response.data.avatar);
                }
              }
            } else {
              // 上传失败
              util.toast('网络异常');
            }
          }
        };

        // let url = 'http://120.24.89.166:520/ar-social/api/user/avatar';
        let url = util.getHost() + '/ar-social/api/user/avatar';
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Authorization', this.$store.state.token);
        xhr.send(formData);
      },

      dataURLtoBlob(dataURL) {
        let binaryString = atob(dataURL.split(',')[1]);
        let arrayBuffer = new ArrayBuffer(binaryString.length);
        let intArray = new Uint8Array(arrayBuffer);
        let mime = dataURL.split(',')[0].match(/:(.*?);/)[1]

        for (let i = 0, j = binaryString.length; i < j; i++) {
          intArray[i] = binaryString.charCodeAt(i);
        }

        let data = [intArray];
        let result = new Blob(data, {
          type: mime
        });
        // console.log(result);
        return result;
      },
      setPhotoType() {
        console.log('setPhotoType type=1');
        var url = 'jsbridge://setSelectType?type=1';
        var iframe = document.createElement('iframe');
        iframe.style.width = '1px';
        iframe.style.height = '1px';
        iframe.style.display = 'none';
        iframe.src = url;
        document.body.appendChild(iframe);
        console.log('setPhotoType over');
        setTimeout(function () {
          iframe.remove();
        }, 100);
      }
    },
    mounted() {
      this.init();
      this.setPhotoType();
    }
  }

</script>

<style lang="less" scoped>
  /*@import "../assets/less/common.less";*/
  #previewer {
    width: 240px;
    height: 240px;
  }

  #filechooser_label {
    color: white;
    background-color: #02a588;
    border-radius: 4px;
    display: inline-block;
    padding: 8px;
    margin: 40px 0px;
  }

  .content {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

</style>
